package com.easychat.redis;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 10 2024/10/2
 */
@Slf4j
@Configuration
public class RedisConfig<V> {
     @Value("${spring.redis.host:}")
     private String redisHost;
     @Value("${spring.redis.port:}")
     private Integer redisPort;

     @Bean
     public RedisTemplate<String,V> redisTemplate(RedisConnectionFactory factory){
          RedisTemplate<String,V> template = new RedisTemplate<>();
          template.setConnectionFactory(factory);
          //字符串序列化器
          StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
          //对象序列化器 GenericJackson2JsonRedisSerializer
          GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
          //设置key的序列化方式
          template.setKeySerializer(stringRedisSerializer);
          //设置value的序列化方式
          template.setValueSerializer(genericJackson2JsonRedisSerializer);
          //设置hash的key的序列化方式
          template.setHashKeySerializer(stringRedisSerializer);
          //设置hash的value的序列化方式
          template.setHashValueSerializer(genericJackson2JsonRedisSerializer);
          template.afterPropertiesSet();
          return template;
     }
     @Bean(name = "redissonClient",destroyMethod = "shutdown")
     public RedissonClient redissonClient(){
          try {
               Config config = new Config();
               config.useSingleServer().setAddress("redis://"+redisHost+":"+redisPort);

               RedissonClient redissonClient = Redisson.create(config);
               log.info("redisson配置完成");
               return redissonClient;

          }catch (Exception e){
               log.error("redis配置错误，请检查redis配置");
          }
          return null;
     }
}
